﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using NLite.Reflection;
using NLite.Internal;

namespace NLite.Mapping.Internal
{
    sealed class PrimitiveMapper : MapperBase
    {
        public PrimitiveMapper(Type fromType, Type toType)
            : base(fromType, toType)
        {
        }

        public override void Map(ref object from, ref object to)
        {
            try
            {
                if (_Info.CanUsingConverter(_Info.Key))
                    to = _Info.converters[_Info.Key].DynamicInvoke(from);
                else
                {
                    if (_Info.From == Types.String)
                    {
                        if (string.IsNullOrEmpty(from as string))
                            to = ObjectCreator.Create(_Info.To);
                        else
                            to = Convert.ChangeType(from, _Info.To);
                    }
                    else
                        to = Convert.ChangeType(from, _Info.To);
                }
            }
            catch (Exception ex)
            {
                var innerEx = ex.GetInnerException();
                throw new InvalidCastException(string.Format("{0} Exception : {1}", Key, innerEx.Message), innerEx);
            }
        }
    }

}
